package org.eduapp.trains.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class UtilsMailHelper {
	
	/**
	 * 发送文本信息邮件
	 * @param sender 邮件发送器
	 * @param to
	 * @param from
	 * @param subject
	 * @param text
	 * @throws Exception
	 */
	public static void sendTextMail (
			final JavaMailSender sender, String to, String from, String subject, String text) throws Exception {
		
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setTo(to);
		if (UtilsString.isNotEmpty(from)) {
			mail.setFrom(from);
		}
		mail.setSubject(subject);
		mail.setText(text);
		
		sender.send(mail);
	}
	
	/**
	 * 发送带附件的邮件
	 * @param sender 邮件发送器
	 * @param to
	 * @param from
	 * @param subject
	 * @param text
	 * @param mimeFiles
	 * @throws Exception
	 */
	public static void sendMimeMessage (
			final JavaMailSender sender, final String to, final String from, final String subject, final String text, List<String> mimeFiles) throws Exception {
		
		// 附件文件集合
		final List<String> files = new ArrayList<String>();
		
		if (mimeFiles != null && mimeFiles.size() > 0) {
			for (String mimeFile : mimeFiles) {
				files.add(mimeFile);
			}
		}
		
		MimeMessagePreparator mimeMail = new MimeMessagePreparator() {
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
				mimeMessage.setFrom(new InternetAddress(from));
				mimeMessage.setSubject(subject);
				
				Multipart mp = new MimeMultipart();
				
				// 添加正文
				MimeBodyPart content = new MimeBodyPart();
				content.setText(text);
				
				mp.addBodyPart(content);
				
				// 添加附件
				for (String file : files) {
					MimeBodyPart attachFile = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(file);
					attachFile.setDataHandler(new DataHandler(fds));
					attachFile.setFileName(fds.getName());
					mp.addBodyPart(attachFile);
				}
				
				files.clear();
				
				mimeMessage.setContent(mp);
				mimeMessage.setSentDate(new Date());
			}
		};
		
		sender.send(mimeMail);
	}
	
}
